<template>
  <div class="main">
    <!-- 查询表单 -->
    <el-form :inline="true" :model="searchMap" class="demo-form-inline showtable" ref="searchMap">
      <el-form-item prop="username">
        <el-input v-model="searchMap.username" placeholder="用户姓名" style="width: 200px;"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <el-button @click="handleAdd" type="success">新增</el-button>
        <el-button @click="$refs['searchMap'].resetFields()">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格显示 -->
    <el-table :data="tableData" border stripe max-height="460" style="width:100%">
      <el-table-column type="index" label="序号" width="205" align="center"></el-table-column>
      <el-table-column prop="username" label="用户姓名" width="300" align="center"></el-table-column>
      <el-table-column prop="phonenum" label="用户手机" width="300" align="center"></el-table-column>
      <el-table-column prop="address" label="收货地址" width="300" align="center"></el-table-column>
      <el-table-column label="操作" width="205" align="center">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页显示 -->
    <div class="fenye">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        hide-on-single-page
      ></el-pagination>
    </div>

    <!-- 对话框 -->
    <el-dialog :title="id?'编辑用户':'新增用户'" :visible.sync="dialogFormVisible" width="500px" top="10px">
      <el-form
        :model="pojo"
        ref="pojoFrom"
        label-width="100px"
        label-position="right"
        style="width: 400px;"
        status-icon
        :rules="rules"
      >
        <el-form-item prop="username" label="用户姓名">
          <el-input v-model="pojo.username" placeholder="用户姓名"></el-input>
        </el-form-item>
        <el-form-item prop="userpass" label="用户密码">
          <el-input v-model="pojo.userpass" placeholder="用户密码"></el-input>
        </el-form-item>
        <el-form-item prop="phonenum" label="用户手机">
          <el-input v-model="pojo.phonenum" placeholder="用户手机"></el-input>
        </el-form-item>
        <el-form-item prop="address" label="收货地址">
          <el-input v-model="pojo.address" placeholder="收货地址"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="id?updataMember('pojoFrom'):addMember('pojoFrom')">确 定</el-button>
        <el-button @click="dialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import memberApi from "@/api/member";
export default {
  data() {
    let checkphone = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入手机号"));
      } else if (!/^1\d{10}$/.test(value)) {
        callback(new Error("请输入正确的手机号码"));
      } else {
        callback();
      }
    };
    return {
      tableData: [],
      currentPage: 1, //当前页
      pageSize: 5, //一页10条数据
      total: null,
      searchMap: {
        //查询条件
        username: ""
      },
      oldDate: 0, //存旧时间
      newDate: 0, //当前时间(毫秒)
      pojo: {
        //新增会员数据
        username: "",
        userpass: "",
        phonenum: "",
        address: ""
      },
      dialogFormVisible: false, //对话框的显示
      rules: {
        //新增会员验证
        username: [
          { required: true, message: "请输入用户名字", trigger: "change" }
        ],
        phonenum: [{ required: true, validator: checkphone, trigger: "blur" }],
        address: [
          { required: true, message: "请输入收货地址", trigger: "blur" }
        ],
        userpass: [
          { required: true, message: "请输入用户密码", trigger: "blur" }
        ]
      },
      id: null
    };
  },

  components: {},

  methods: {
    //查询用户
    async searchUser({ username }) {
      try {
        let p = await memberApi.searchman(username);
        if (p.data.flag) {
          if (p.data.data.length > this.pageSize) {
            let arr = [];
            for (let i = 0; i < this.pageSize; i++) {
              arr.push(p.data.data[i]);
            }
            this.tableData = arr;
          } else {
            this.tableData = p.data.data;
          }
          this.total = p.data.total;
        }
      } catch (err) {
        console.log(err);
      }
    },
    //点击查询
    onSubmit() {
      let istrue = this.clickToFast();
      if (istrue) {
        this.searchUser(this.searchMap);
        console.log("过了800毫秒了");
      } else {
        console.log("还没过800毫秒");
      }
    },
    //获取分页数据
    async getSearch() {
      try {
        //把要第几页、一页多少条、查询条件一并发给后端
        let p = await memberApi.search(this.currentPage, this.pageSize);
        if (p.data.flag) {
          this.tableData = p.data.data;
          this.total = p.data.total;
        }
      } catch (err) {
        console.log(err);
      }
    },
    //更换一页条数
    handleSizeChange(val) {
      //val  是当页面条数发生改变时 传入得新值  如  当页面初始条数是10 点击更换成20条 那val就是20
      this.pageSize = val;
      this.getSearch();
    },
    //更换当前页码
    handleCurrentChange(val) {
      //val 当点击更换当前页时  val就是要更换得页码数
      this.currentPage = val;
      this.getSearch();
    },
    //修改信息
    handleEdit(row) {
      this.dialogFormVisible = true;
      this.id = row.userid;
      for (let key in this.pojo) {
        this.pojo[key] = row[key];
      }
    },
    //删除用户
    handleDelete(row) {
      this.$confirm("确定要删除该用户吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleteUser(row.username);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //删除用户，请求ajax
    async deleteUser(username) {
      try {
        let p = await memberApi.deleteMember(username);
        if (p.data.flag) {
          this.$message({
            type: "success",
            message: "删除成功!"
          });
          // this.tableData=this.tableData.filter(item => {
          //   return item.username != username;
          // });
          this.getSearch();
        } else {
          this.$message({
            type: "erroe",
            message: "删除失败!"
          });
        }
      } catch (err) {
        console.log("ajax请求失败", err);
      }
    },
    //对话框显示t
    handleAdd() {
      this.id = null;
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        //this.$nextTick() 它是一个异步事件，当渲染结束 之后，它的回调函数才被执行
        this.pojo = {
          //新增会员数据
          username: "",
          userpass: ""
        };
        this.$refs["pojoFrom"].resetFields();
      });
    },
    //新增信息
    addMember(pojoFrom) {
      this.$refs[pojoFrom].validate(valid => {
        if (valid) {
          //表单正则验证通过 发送ajax
          this.addUser(this.pojo);
        } else {
          //正则验证不通过
          this.$message({
            message: "请把必填的填写完整",
            type: "error"
          });
        }
      });
    },
    //添加一个新会员 发送ajax
    async addUser(pojo) {
      try {
        let p = await memberApi.addMember(pojo);
        if (p.data.flag) {
          //新增成功
          this.$message({
            message: "添加成功",
            type: "success"
          });
          this.dialogFormVisible = false;
          // this.tableData.unshift(pojo);
          this.getSearch();
        } else {
          //新增失败
          this.$message({
            message: "添加失败",
            type: "error"
          });
        }
      } catch (err) {
        //ajax 报错
        console.log("发送ajax失败", err);
      }
    },
    //防止点击过快
    clickToFast() {
      this.oldDate = this.newDate;
      this.newDate = new Date().getTime();
      if (this.newDate - this.oldDate > 800) {
        return true;
      } else {
        return false;
      }
    },
    //更新用户
    updataMember(pojoFrom) {
      this.$refs[pojoFrom].validate(vaild => {
        if (vaild) {
          this.updataUser(this.id, this.pojo);
        } else {
          this.$message({
            message: "亲，您还没填完噢",
            type: "error"
          });
        }
      });
    },
    //请求ajax 更新用户
    async updataUser(id, obj) {
      try {
        let p = await memberApi.updataMember(id, obj);
        if (p.data.flag) {
          this.$message({
            message: "编辑成功",
            type: "success"
          });
          this.dialogFormVisible = false;
          this.tableData.forEach(item => {
            if (item.userid == id) {
              for (let key in obj) {
                item[key] = obj[key];
              }
            }
          });
          // this.getSearch();
        } else {
          this.$message({
            message: "编辑失败",
            type: "error"
          });
        }
      } catch (err) {
        console.log("ajax请求出错", err);
      }
    }
  },
  created() {
    this.getSearch();
  }
};
</script>

<style scoped lang="scss">
.main {
  height: 80%;
}
</style>